package hr.cars.functional.stepdefs;

import cucumber.annotation.en.Given;
import cucumber.runtime.PendingException;
import cucumber.table.DataTable;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.LinkedList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: VMoskalenko
 * Date: 05.07.12
 * Time: 13:01
 */
public class JdbcSteps {

    @Given("^employees in database$")
    public void employees_in_database(List<Employee> employees) {
        ApplicationContext context = new ClassPathXmlApplicationContext("acceptance-test-context.xml");
        JdbcTemplate jdbcTemplate = new JdbcTemplate((DataSource) context.getBean("dataSource"));
        jdbcTemplate.update("delete from Employee");
        int index = 1;
        List<String> sqlStatements = new LinkedList<String>();
        for (Employee employee : employees) {
            sqlStatements.add(buildSql(index++, employee));
        }
        jdbcTemplate.batchUpdate(sqlStatements.toArray(new String[sqlStatements.size()]));
    }

    private String buildSql(int index, Employee employee) {
        return String.format("insert into EMPLOYEE (id, firstName, lastName, jobTitle) values (%1$d,    '%2$s', '%3$s', '%4$s')",
                index, employee.firstName, employee.lastName, employee.jobTitle);
    }


    public static class Employee {
        public String firstName;
        public String lastName;
        public String jobTitle;
    }
}
